package com.example.testproject.activity

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityOptionsCompat
import com.example.testproject.R
import com.example.testproject.ext.click
import kotlinx.android.synthetic.main.activity_result_api_first.*


/**
 *
 * @ClassName: ResultApiFirstActivity
 * @Author: android 超级兵
 * @CreateDate: 11/3/21$ 9:26 AM$
 * TODO  废弃 startActivityForResult() 推荐使用Activity Result API 测试
 */
class ResultApiFirstActivity : AppCompatActivity() {

    companion object {
        const val RESULT_CODE = 200
        const val REQUEST_CODE = 201

        // 需要传递数据的key
        const val TRANSMIT_DATA = "first_data"
    }

    private val str = "我是first的数据"

    /*
     * 作者:android 超级兵
     * 创建时间: 11/3/21 10:20 AM
     *
     * 目前其他的 contract
     * TODO StartActivityForResult()
            StartIntentSenderForResult()
            RequestMultiplePermissions()
            RequestPermission()
            TakePicturePreview()
            TakePicture()
            TakeVideo()
            PickContact()
            GetContent()
            GetMultipleContents()
            OpenDocument()
            OpenMultipleDocuments()
            OpenDocumentTree()
            CreateDocument()
     */

    // 打开摄像头
    private val requestTakeVideoDataLauncher =
        registerForActivityResult(ActivityResultContracts.TakeVideo(),
            object : ActivityResultRegistry() {
                override fun <I : Any?, O : Any?> onLaunch(
                    requestCode: Int,
                    contract: ActivityResultContract<I, O>,
                    input: I,
                    options: ActivityOptionsCompat?,
                ) {

                }
            }) {
            imageVideo.setImageBitmap(it)

        }


    /*
     * 作者:android 超级兵
     * 创建时间: 11/3/21 10:01 AM
     * TODO 跳转页面,并接受返回值
     */
    private val requestDataLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

            tvHead.text = result.data?.data?.toString() ?: "??"
            if (result.resultCode == RESULT_CODE) {
                tvHead.text =
                    result?.data?.getStringExtra(ResultApiSecondActivity.SECOND_TRANSMIT_DATA)
                        ?: "没有接收到数据啊"
            }
        }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/3/21 10:02 AM
     * TODO 申请权限
     */
    private val requestPermissionDataLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isSuccess ->
            tvHead.text = if (isSuccess) {
                // 手机拍摄图片获取bitmap [切记申请相机权限]
                // requestPhotoDataLauncher.launch(null)
                "申请的权限都通过啦"
            } else "申请的权限未通过啊"
        }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/3/21 10:08 AM
     * TODO 手机拍摄图片获取bitmap [切记申请相机权限]
     */
    private val requestPhotoDataLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicturePreview()) { bitmap ->
            tvHead.text = bitmap.toString()
        }


    private val requestPermissions: ActivityResultLauncher<Array<String>> =
        registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) { result ->
            for (entry in result) {
                Toast.makeText(
                    this@ResultApiFirstActivity,
                    entry.key + " " + entry.value,
                    Toast.LENGTH_SHORT
                )
                    .show()
            }
        }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result_api_first)

        tvHead.text = str

        val intent = Intent(this, ResultApiSecondActivity::class.java)
        intent.putExtra(TRANSMIT_DATA, str)

        // 旧版写法
//        btFirst.setOnClickListener {
//            startActivityForResult(intent, REQUEST_CODE)
//        }

        // activity result api 最新版写法
        btFirst.setOnClickListener {
            // 跳转页面测试
//            requestDataLauncher.launch(intent)

            // 申请权限测试 [记得在androidManifest.xml中申请]
//            requestPermissionDataLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
//            requestPermissionDataLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//            requestPermissionDataLauncher.launch(Manifest.permission.CAMERA)

            val packageURI = Uri.parse("package:" + getPackageName())
            val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
            startActivity(intent)
//            requestPermissions.launch(
//                arrayOf(
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                    Manifest.permission.CAMERA,
//                )
//            )

            // 手机拍摄图片获取bitmap [切记申请相机权限]
//            requestPhotoDataLauncher.launch(null)
        }

        btVideo.click {
            requestDataLauncher.launch(Intent(MediaStore.ACTION_VIDEO_CAPTURE))
//            handleRecordVideoRequest()
        }


    }

    /*
     * 作者:android 超级兵
     * 创建时间: 11/3/21 9:55 AM
     * TODO 旧版写法[appcompat1.3.0之上已经不推荐使用了!],需要回调onActivityResult()
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_CODE && requestCode == REQUEST_CODE) {
            tvHead.text =
                data?.getStringExtra(ResultApiSecondActivity.SECOND_TRANSMIT_DATA) ?: "没有接收到数据啊"
        } else {
            tvHead.text = "requestCode 匹配不上啊"
        }
    }
}